package cn.daman.chineseol.handler;

import cn.daman.chineseol.entity.Message;
import cn.daman.chineseol.entity.User;
import cn.daman.chineseol.utils.DataTool;
import cn.daman.chineseol.utils.UserTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/msg")
public class MsgHandler {
    @Autowired
    private DataTool dataTool;
    @Autowired
    private UserTool userTool;
    @GetMapping("/get/{page}")
    public Map<String, Object> get(@PathVariable Integer page, @RequestParam(defaultValue = "10") Integer size){
        Pageable pageable = PageRequest.of(page-1, size, Sort.Direction.DESC, "theTime");
        Page<Message> pageList = dataTool.msgRepo.findAll(pageable);

        List<Message> msgList = pageList.getContent();
        Map<String, Object> map = new HashMap<>();

        map.put("totalPages", pageList.getTotalPages());
        List<Map<String, Object>> list = new ArrayList<>();

        for (Message m : msgList){
            Map<String, Object> elem = new HashMap<>();
            elem.put("content", m);
            elem.put("u", dataTool.userRepo.findById(m.getUid()).get());
            list.add(elem);
        }

        map.put("list", list);
        return map;
    }
    @PostMapping("/send")
    public void send(@RequestBody Message message, HttpSession session){
        message.setTheTime(new Date());
        User user = userTool.getUser(session);
        message.setUid(user.getId());
        dataTool.msgRepo.save(message);
    }
}
